window.onload = function() {

	oDiv1 = document.getElementById('div1');
	oDiv2 = document.getElementById('div2');

	drag(oDiv1);
	drag(oDiv2);

};

var oDiv1 = null;
var oDiv2 = null;

function drag(obj) {
	obj.onmousedown = function(ev) {
		ev = ev || event;

		var disX = ev.clientX - this.offsetLeft;
		var disY = ev.clientY - this.offsetTop;

		if(this.setCapture) {
			this.setCapture();
		}

		document.onmousemove = function(ev) {
			ev = ev || event;

			var left = ev.clientX - disX;
			var top = ev.clientY - disY;

			// 磁性吸附
			var clientWidth = document.documentElement.clientWidth || 
				document.body.clientWidth;
			var clientHeight = document.documentElement.clientHeight || 
				document.body.clientHeight;

			var leftMin = 100;
			var leftMax = clientWidth -	obj.offsetWidth - 100;
			var topMin = 100;
			var topMax = clientHeight - obj.offsetHeight - 100;

			if (left < leftMin) {
				left = 0;
			}

			if (left > leftMax) {
				left = leftMax + 100;
			}

			if( top < topMin ) {
				top = 0;
			}

			if( top > topMax ) {
				top = topMax + 100;
			}

			obj.style.left = left + 'px';
			obj.style.top = top + 'px';

		};

		document.onmouseup = function() {
			document.onmousemove = null;
			document.onmouseup = null;

			if(obj.releaseCapture) {
				obj.releaseCapture();
			}
		};
		return false;
	};
}
